import pandas as pd
def gradient_strategy_diff(base_input, user_input, base_input_index, user_input_index, frame_num):
    # 1.先计算 10秒内的平均梯度
    base_frames_num = len(base_input)
    user_frames_num = len(user_input)
    if base_frames_num < 240 or user_frames_num < 240:
        raise Exception("请传入时长大于10秒的视频！")
    ten_second_frames_base = base_input[base_input_index: 240 + base_input_index]
    ten_second_frame_user = user_input[user_input_index: 240 + user_input_index]
    baseline_columns = _calc_diff_columns(ten_second_frames_base, ten_second_frame_user, 0, 0)
    # 2.以此梯度作为基准 计算全视频的差值
    # 下面开始真正计算分数
    base_input = base_input[base_input_index:]
    user_input = user_input[user_input_index:]
    gradients_delta_all = []
    for i in range(min(len(base_input), len(user_input))):
        frame_base_key_points = base_input[i][0].key_points
        frame_user_key_points = user_input[i][0].key_points
        gradients_delta = []
        for j in range(0, len(frame_base_key_points)):
            # 差值绝对值的和 除以帧数 得到分数
            base_key_point = frame_base_key_points[j]
            user_key_point = frame_user_key_points[j]
            gradient = _get_gradient(base_key_point, user_key_point)
            base_gradient = baseline_columns[j]
            delta = abs(gradient - base_gradient)
            gradients_delta.append(delta)
        gradients_delta_all.append(gradients_delta)
    gradients_delta_all_df = pd.DataFrame(gradients_delta_all)
    return gradients_delta_all_df.sum(axis=0).sum()




def _calc_diff_columns(frames_base, frames_user, frame_base_start_index, frame_user_start_index):
    gradients_all = []
    for i in range(0, min(len(frames_base), len(frames_user))):
        frame_base_key_points = frames_base[frame_base_start_index + i][0].key_points
        frame_user_key_points = frames_user[frame_user_start_index + i][0].key_points
        if len(frame_base_key_points) != len(frame_user_key_points):
            raise Exception(print("关键点个数不匹配！"))
        gradients = []
        for j in range(0, len(frame_base_key_points)):  # 对每个关键点计算梯度
            base_key_point = frame_base_key_points[j]
            user_key_point = frame_user_key_points[j]
            gradient = _get_gradient(base_key_point, user_key_point)
            gradients.append(gradient)
        gradients_all.append(gradients)
    # gradients_all是一个x行（x为参与计算的标志点个数）y列（列为frame frame_num）
    gradients_all_df = pd.DataFrame(gradients_all)
    mean_df = gradients_all_df.mean(axis=0)
    return mean_df.to_list()


def _get_gradient(coordinate_base, coordinate_user):  # y1- y0 / x1 - x0
    coordinate_base_x, coordinate_base_y, _ = coordinate_base
    coordinate_user_x, coordinate_user_y, _ = coordinate_user
    if (coordinate_user_x - coordinate_base_x) == 0:
        return 0
    gradient = (coordinate_user_y - coordinate_base_y) / (coordinate_user_x - coordinate_base_x)
    return gradient